local resty_rsa = require "rsa"

local rsa_public_key = [[-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkl2ygbgaM8AcwakO+8EDigWZ8
XFFacYD6+OKFf8GlY19amIwrybYj+h5GSpVVuOfOG/AFpmFL4ig/735mJCOzxaGN
XUsbi19yKVuSIqPF+OZKMuFGZDu+aXfCKIWwSoFih6hbiVzvJ9cc2KjnNQlqpHgr
UuENtHcH+EDJThHwZQIDAQAB
-----END PUBLIC KEY-----]]

local chunk, eof = ngx.arg[1], ngx.arg[2]

ngx.ctx.response_body = ngx.ctx.response_body or ""

if chunk then
    ngx.ctx.response_body = ngx.ctx.response_body .. chunk

    if not eof then
        local pub, err = resty_rsa:new({
            public_key = rsa_public_key,
            key_type = resty_rsa.KEY_TYPE.PKCS8,
        })

        if not pub then
            ngx.log(ngx.ERR, "new rsa err:" .. err)
            return
        end

        ngx.arg[1] = ngx.encode_base64(pub:encrypt(ngx.ctx.response_body))
        ngx.log(ngx.INFO, ngx.arg[1])
        return
    end
end                                                                                                        
